package utils

import (
	"errors"
	"github.com/golang-jwt/jwt/v5"
	"github.com/google/uuid"
	"time"
)

type CustomPayload struct {
	Username   string `json:"user"`
	GrantScope string
	jwt.RegisteredClaims
}

func GenerateJwtToken(username string, subject string, secret string, ttl time.Duration) (string, error) {
	claim := CustomPayload{
		Username:   username,
		GrantScope: subject,
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    "Auth_Server",                                   //签发者
			Subject:   subject,                                         //签发对象
			Audience:  jwt.ClaimStrings{"PC", "web"},                   //签发受众
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(ttl)),         //过期时间
			NotBefore: jwt.NewNumericDate(time.Now().Add(time.Second)), //最早使用时间
			IssuedAt:  jwt.NewNumericDate(time.Now()),                  //签发时间
		},
	}
	token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claim).SignedString([]byte(secret))
	return token, err
}

func ParseJwtToken(token string, secret string) (*CustomPayload, error) {
	// 解析token
	parseToken, err := jwt.ParseWithClaims(token, &CustomPayload{}, func(token *jwt.Token) (i interface{}, err error) {
		return []byte(secret), nil
	})
	if err != nil {
		return nil, err
	}
	if claims, ok := parseToken.Claims.(*CustomPayload); ok && parseToken.Valid { // 校验token
		return claims, nil
	}
	return nil, errors.New("invalid token")
}
func GenerateToken() string {
	uid := uuid.New().String()
	return uid
}
